﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.IO;

namespace SubBoard_Simulator
{
    public partial class Form1 : Form
    {
        public Thread sending_thread, receive_thread, sending_init;
        string txtPath = Application.StartupPath;
        public string RxString = "", newFileName = "logfile.txt", comport_name = "comport.txt", logfile_path,
            comport_path, comport_str = "Com13", ack_str = (char)0x02 + "a66" + (char)0x03, nack_str = (char)0x02 + "n73" + (char)0x03, sub_RxString;
        public char[] Rcv_array = new char[30];
        public Semaphore accessing_sem = new Semaphore(1, 1), transceiver_sem = new Semaphore(1, 1);
        public int[] led_state = { 0, 0, 0 }, led_color = { 1, 1, 1 };
        public int nack_count = 0;
        public bool initcmd_flag = false;
        public Form1()
        {
            InitializeComponent();
        }
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            accessing_sem.WaitOne();
            char ext_char = (char)0x03;
            sub_RxString += serialPort1.ReadExisting();
            if (sub_RxString != "")
            {
                if (sub_RxString.Substring(sub_RxString.Length - 1, 1) == ext_char.ToString())
                {
                    if (radioButton3.Checked)
                    {
                        serialPort1.Close();
                        System.IO.File.AppendAllText(logfile_path, DateTime.Now.ToLongTimeString() + ": Disconnect 2");
                        accessing_sem.Release();
                        return;
                    }
                    RxString = sub_RxString;
                    sub_RxString = "";
                    Rcv_array = RxString.ToCharArray();
                    string s = "";
                    for (int cnt = 0; cnt < Rcv_array.Length; cnt++)
                    {
                        if (Rcv_array[cnt] < 32 || Rcv_array[cnt] > 126)
                            s += Convert.ToInt32(Rcv_array[cnt]).ToString("x2");
                        else
                            s += Rcv_array[cnt];
                    }
                    this.Invoke((MethodInvoker)delegate()
                    {
                        richTextBox1.SelectionStart = richTextBox1.TextLength;
                        richTextBox1.SelectionLength = 0;
                        richTextBox1.SelectionColor = Color.Red;
                        s = DateTime.Now.ToLongTimeString() + ":" + s + "\r\n";
                        richTextBox1.AppendText(s);
                        richTextBox1.SelectionColor = richTextBox1.ForeColor;
                        System.IO.File.AppendAllText(logfile_path, s);
                        if (richTextBox1.Text.Length >= 32000)
                            richTextBox1.Text = "";
                        richTextBox1.SelectionStart = richTextBox1.Text.Length;
                        richTextBox1.ScrollToCaret();
                    });
                    if (radioButton2.Checked)
                    {
                        serialPort1.Close();
                        System.IO.File.AppendAllText(logfile_path, DateTime.Now.ToLongTimeString() + ": Disconnect 1");
                        accessing_sem.Release();
                        return;
                    }
                    receive_thread = new Thread(recv_funtion);
                    receive_thread.Start();
                }
            }
            accessing_sem.Release();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            System.Diagnostics.Process MY = System.Diagnostics.Process.GetCurrentProcess();
            MY.PriorityClass = System.Diagnostics.ProcessPriorityClass.High;
            logfile_path = System.IO.Path.Combine(txtPath, newFileName);
            comport_path = System.IO.Path.Combine(txtPath, comport_name);
            System.IO.File.WriteAllText(logfile_path, "");
            if (!System.IO.File.Exists(comport_path))
            {
                comport comport_form = new comport(this);
                comport_form.ShowDialog();
            }
            if (!serialPort1.IsOpen)
            {
                StreamReader file = System.IO.File.OpenText(comport_path);
                serialPort1.PortName = file.ReadLine();
                try
                {
                    serialPort1.BaudRate = Convert.ToInt32(file.ReadLine());
                    serialPort1.DataBits = Convert.ToInt32(file.ReadLine());

                    serialPort1.Encoding = Encoding.GetEncoding(28591);
                    switch (file.ReadLine())
                    {
                        case "0":
                            serialPort1.StopBits = System.IO.Ports.StopBits.None;
                            break;
                        case "1":
                            serialPort1.StopBits = System.IO.Ports.StopBits.One;
                            break;
                        case "1.5":
                            serialPort1.StopBits = System.IO.Ports.StopBits.OnePointFive;
                            break;
                        case "2":
                            serialPort1.StopBits = System.IO.Ports.StopBits.Two;
                            break;
                        default:
                            break;
                    }
                    switch (file.ReadLine())
                    {
                        case "None":
                            serialPort1.Parity = System.IO.Ports.Parity.None;
                            break;
                        case "Even":
                            serialPort1.Parity = System.IO.Ports.Parity.Even;
                            break;
                        case "Old":
                            serialPort1.Parity = System.IO.Ports.Parity.Odd;
                            break;
                        default:
                            break;
                    }
                    serialPort1.Handshake = System.IO.Ports.Handshake.None;
                    serialPort1.ReadTimeout = 4000;
                    serialPort1.WriteTimeout = 4000;
                    serialPort1.Open();
                    file.Close();
                }
                catch
                {
                    try
                    {
                        file.Close();
                    }
                    catch { }
                    comport comport_form = new comport(this);
                    comport_form.ShowDialog();
                    return;
                }
            }
        }
        public void sending_funtion()
        {
            try
            {
                accessing_sem.WaitOne();
                this.Invoke((MethodInvoker)delegate()
                {
                    if (radioButton5.Checked)
                    {
                        string append_str = DateTime.Now.ToLongTimeString() + ":" +
                            ack_str.Substring(0, 3).Replace(((char)0x02).ToString(), "02");
                        serialPort1.Write(ack_str.Substring(0, 3));
                        richTextBox1.AppendText(append_str);
                        richTextBox1.SelectionStart = richTextBox1.Text.Length;
                        richTextBox1.ScrollToCaret();
                        System.IO.File.AppendAllText(logfile_path, append_str);
                        if (radioButton4.Checked)
                        {
                            serialPort1.Close();
                            System.IO.File.AppendAllText(logfile_path, DateTime.Now.ToLongTimeString() + ": Disconnect 3");
                            return;
                        }
                        append_str = ack_str.Substring(3, ack_str.Length - 3).Replace(((char)0x03).ToString(), "03") + "\r\n";
                        serialPort1.Write(ack_str.Substring(3, ack_str.Length - 3));
                        richTextBox1.AppendText(append_str);
                        richTextBox1.SelectionStart = richTextBox1.Text.Length;
                        richTextBox1.ScrollToCaret();
                        System.IO.File.AppendAllText(logfile_path, append_str);
                    }
                    else if (radioButton6.Checked)
                    {
                        if (nack_count < 1)
                        {
                            string append_str = DateTime.Now.ToLongTimeString() + ":" +
                                nack_str.Substring(0, 3).Replace(((char)0x02).ToString(), "02");
                            serialPort1.Write(nack_str.Substring(0, 3));
                            richTextBox1.AppendText(append_str);
                            richTextBox1.SelectionStart = richTextBox1.Text.Length;
                            richTextBox1.ScrollToCaret();
                            System.IO.File.AppendAllText(logfile_path, append_str);
                            if (radioButton4.Checked)
                            {
                                serialPort1.Close();
                                System.IO.File.AppendAllText(logfile_path, DateTime.Now.ToLongTimeString() + ": Disconnect 3");
                                return;
                            }
                            append_str = nack_str.Substring(3, nack_str.Length - 3).Replace(((char)0x03).ToString(), "03") + "\r\n";
                            serialPort1.Write(nack_str.Substring(3, nack_str.Length - 3));
                            richTextBox1.AppendText(append_str);
                            richTextBox1.SelectionStart = richTextBox1.Text.Length;
                            richTextBox1.ScrollToCaret();
                            System.IO.File.AppendAllText(logfile_path, append_str);
                            nack_count++;
                        }
                        else if (nack_count >= 1)
                        {
                            string append_str = DateTime.Now.ToLongTimeString() + ":" +
                                ack_str.Substring(0, 3).Replace(((char)0x02).ToString(), "02");
                            serialPort1.Write(ack_str.Substring(0, 3));
                            richTextBox1.AppendText(append_str);
                            richTextBox1.SelectionStart = richTextBox1.Text.Length;
                            richTextBox1.ScrollToCaret();
                            System.IO.File.AppendAllText(logfile_path, append_str);
                            if (radioButton4.Checked)
                            {
                                serialPort1.Close();
                                System.IO.File.AppendAllText(logfile_path, DateTime.Now.ToLongTimeString() + ": Disconnect 3");
                                return;
                            }
                            append_str = ack_str.Substring(3, ack_str.Length - 3).Replace(((char)0x03).ToString(), "03") + "\r\n";
                            serialPort1.Write(ack_str.Substring(3, ack_str.Length - 3));
                            richTextBox1.AppendText(append_str);
                            richTextBox1.SelectionStart = richTextBox1.Text.Length;
                            richTextBox1.ScrollToCaret();
                            System.IO.File.AppendAllText(logfile_path, append_str);
                            nack_count = 0;
                        }
                    }
                    else if (radioButton7.Checked)
                    {
                        if (nack_count < 2)
                        {
                            string append_str = DateTime.Now.ToLongTimeString() + ":" +
                                nack_str.Substring(0, 3).Replace(((char)0x02).ToString(), "02");
                            serialPort1.Write(nack_str.Substring(0, 3));
                            richTextBox1.AppendText(append_str);
                            richTextBox1.SelectionStart = richTextBox1.Text.Length;
                            richTextBox1.ScrollToCaret();
                            System.IO.File.AppendAllText(logfile_path, append_str);
                            if (radioButton4.Checked)
                            {
                                serialPort1.Close();
                                System.IO.File.AppendAllText(logfile_path, DateTime.Now.ToLongTimeString() + ": Disconnect 3");
                                return;
                            }
                            append_str = nack_str.Substring(3, nack_str.Length - 3).Replace(((char)0x03).ToString(), "03") + "\r\n";
                            serialPort1.Write(nack_str.Substring(3, nack_str.Length - 3));
                            richTextBox1.AppendText(append_str);
                            richTextBox1.SelectionStart = richTextBox1.Text.Length;
                            richTextBox1.ScrollToCaret();
                            System.IO.File.AppendAllText(logfile_path, append_str);
                            nack_count++;
                        }
                        else if (nack_count >= 2)
                        {
                            string append_str = DateTime.Now.ToLongTimeString() + ":" +
                                ack_str.Substring(0, 3).Replace(((char)0x02).ToString(), "02");
                            serialPort1.Write(ack_str.Substring(0, 3));
                            richTextBox1.AppendText(append_str);
                            richTextBox1.SelectionStart = richTextBox1.Text.Length;
                            richTextBox1.ScrollToCaret();
                            System.IO.File.AppendAllText(logfile_path, append_str);
                            if (radioButton4.Checked)
                            {
                                serialPort1.Close();
                                System.IO.File.AppendAllText(logfile_path, DateTime.Now.ToLongTimeString() + ": Disconnect 3");
                                return;
                            }
                            append_str = ack_str.Substring(3, ack_str.Length - 3).Replace(((char)0x03).ToString(), "03") + "\r\n";
                            serialPort1.Write(ack_str.Substring(3, ack_str.Length - 3));
                            richTextBox1.AppendText(append_str);
                            richTextBox1.SelectionStart = richTextBox1.Text.Length;
                            richTextBox1.ScrollToCaret();
                            System.IO.File.AppendAllText(logfile_path, append_str);
                            nack_count = 0;
                        }
                    }
                    else if (radioButton8.Checked)
                    {
                        if (nack_count < 3)
                        {
                            string append_str = DateTime.Now.ToLongTimeString() + ":" +
                                nack_str.Substring(0, 3).Replace(((char)0x02).ToString(), "02");
                            serialPort1.Write(nack_str.Substring(0, 3));
                            richTextBox1.AppendText(append_str);
                            richTextBox1.SelectionStart = richTextBox1.Text.Length;
                            richTextBox1.ScrollToCaret();
                            System.IO.File.AppendAllText(logfile_path, append_str);
                            if (radioButton4.Checked)
                            {
                                serialPort1.Close();
                                System.IO.File.AppendAllText(logfile_path, DateTime.Now.ToLongTimeString() + ": Disconnect 3");
                                return;
                            }
                            append_str = nack_str.Substring(3, nack_str.Length - 3).Replace(((char)0x03).ToString(), "03") + "\r\n";
                            serialPort1.Write(nack_str.Substring(3, nack_str.Length - 3));
                            richTextBox1.AppendText(append_str);
                            richTextBox1.SelectionStart = richTextBox1.Text.Length;
                            richTextBox1.ScrollToCaret();
                            System.IO.File.AppendAllText(logfile_path, append_str);
                            nack_count++;
                        }
                        else if (nack_count >= 3)
                        {
                            string append_str = DateTime.Now.ToLongTimeString() + ":" +
                                ack_str.Substring(0, 3).Replace(((char)0x02).ToString(), "02");
                            serialPort1.Write(ack_str.Substring(0, 3));
                            richTextBox1.AppendText(append_str);
                            richTextBox1.SelectionStart = richTextBox1.Text.Length;
                            richTextBox1.ScrollToCaret();
                            System.IO.File.AppendAllText(logfile_path, append_str);
                            if (radioButton4.Checked)
                            {
                                serialPort1.Close();
                                System.IO.File.AppendAllText(logfile_path, DateTime.Now.ToLongTimeString() + ": Disconnect 3");
                                return;
                            }
                            append_str = ack_str.Substring(3, ack_str.Length - 3).Replace(((char)0x03).ToString(), "03") + "\r\n";
                            serialPort1.Write(ack_str.Substring(3, ack_str.Length - 3));
                            richTextBox1.AppendText(append_str);
                            richTextBox1.SelectionStart = richTextBox1.Text.Length;
                            richTextBox1.ScrollToCaret();
                            System.IO.File.AppendAllText(logfile_path, append_str);
                            nack_count = 0;
                        }
                    }
                });
                accessing_sem.Release();
            }
            catch (ThreadInterruptedException)
            {
                return;
            }
        }
        public void sendinginit_funtion()
        {
            try
            {
                accessing_sem.WaitOne();
                this.Invoke((MethodInvoker)delegate()
                {
                    if (radioButton9.Checked)
                    {
                        string init_str = (char)0x02 + "a";
                        init_str += textBox3.Text.Length > 0 ? (int.Parse(textBox3.Text, System.Globalization.NumberStyles.HexNumber)).ToString("x8").ToUpper() : "00000000";
                        init_str += textBox4.Text.Length > 0 ? (int.Parse(textBox4.Text, System.Globalization.NumberStyles.HexNumber)).ToString("x8").ToUpper() : "00000000";
                        init_str += textBox5.Text.Length > 0 ? (int.Parse(textBox5.Text, System.Globalization.NumberStyles.HexNumber)).ToString("x8").ToUpper() : "00000000";
                        init_str += textBox6.Text.Length > 0 ? (int.Parse(textBox6.Text, System.Globalization.NumberStyles.HexNumber)).ToString("x8").ToUpper() : "00000000";
                        init_str += textBox7.Text.Length > 0 ? (int.Parse(textBox7.Text, System.Globalization.NumberStyles.HexNumber)).ToString("x8").ToUpper() : "00000000";
                        char[] init_array = init_str.Substring(1, init_str.Length - 1).ToArray();
                        int checksum = 0;
                        for (int i = 0; i < init_array.LongLength; i++)
                        {
                            checksum += init_array[i];
                        }
                        checksum += 0x05;
                        checksum %= 0x100;
                        init_str += checksum.ToString("x2").ToUpper() + (char)0x03;
                        string append_str = DateTime.Now.ToLongTimeString() + ":" +
                            init_str.Substring(0, 3).Replace(((char)0x02).ToString(), "02");
                        serialPort1.Write(init_str.Substring(0, 3));
                        richTextBox1.AppendText(append_str);
                        richTextBox1.SelectionStart = richTextBox1.Text.Length;
                        richTextBox1.ScrollToCaret();
                        System.IO.File.AppendAllText(logfile_path, append_str);
                        if (radioButton4.Checked)
                        {
                            serialPort1.Close();
                            System.IO.File.AppendAllText(logfile_path, DateTime.Now.ToLongTimeString() + ": Disconnect 3");
                            accessing_sem.Release();
                            return;
                        }
                        append_str = init_str.Substring(3, init_str.Length - 3).Replace(((char)0x03).ToString(), "03") + "\r\n";
                        serialPort1.Write(init_str.Substring(3, init_str.Length - 3));
                        richTextBox1.AppendText(append_str);
                        richTextBox1.SelectionStart = richTextBox1.Text.Length;
                        richTextBox1.ScrollToCaret();
                        System.IO.File.AppendAllText(logfile_path, append_str);
                    }
                    else
                    {
                        string init_str = (char)0x02 + "N";
                        init_str += textBox12.Text.Length > 0 ? (int.Parse(textBox12.Text, System.Globalization.NumberStyles.HexNumber)).ToString("x8").ToUpper() : "00000000";
                        init_str += textBox8.Text.Length > 0 ? (int.Parse(textBox8.Text, System.Globalization.NumberStyles.HexNumber)).ToString("x8").ToUpper() : "00000000";
                        init_str += textBox9.Text.Length > 0 ? (int.Parse(textBox9.Text, System.Globalization.NumberStyles.HexNumber)).ToString("x8").ToUpper() : "00000000";
                        init_str += textBox10.Text.Length > 0 ? (int.Parse(textBox10.Text, System.Globalization.NumberStyles.HexNumber)).ToString("x8").ToUpper() : "00000000";
                        init_str += textBox11.Text.Length > 0 ? (int.Parse(textBox11.Text, System.Globalization.NumberStyles.HexNumber)).ToString("x8").ToUpper() : "00000000";
                        char[] init_array = init_str.Substring(1, init_str.Length - 1).ToArray();
                        int checksum = 0;
                        for (int i = 0; i < init_array.LongLength; i++)
                        {
                            checksum += init_array[i];
                        }
                        checksum += 0x05;
                        checksum %= 0x100;
                        init_str += checksum.ToString("x2").ToUpper() + (char)0x03;
                        string append_str = DateTime.Now.ToLongTimeString() + ":" +
                            init_str.Substring(0, 3).Replace(((char)0x02).ToString(), "02");
                        serialPort1.Write(init_str.Substring(0, 3));
                        richTextBox1.AppendText(append_str);
                        richTextBox1.SelectionStart = richTextBox1.Text.Length;
                        richTextBox1.ScrollToCaret();
                        System.IO.File.AppendAllText(logfile_path, append_str);
                        if (radioButton4.Checked)
                        {
                            serialPort1.Close();
                            System.IO.File.AppendAllText(logfile_path, DateTime.Now.ToLongTimeString() + ": Disconnect 3");
                            accessing_sem.Release();
                            return;
                        }
                        append_str = init_str.Substring(3, init_str.Length - 3).Replace(((char)0x03).ToString(), "03") + "\r\n";
                        serialPort1.Write(init_str.Substring(3, init_str.Length - 3));
                        richTextBox1.AppendText(append_str);
                        richTextBox1.SelectionStart = richTextBox1.Text.Length;
                        richTextBox1.ScrollToCaret();
                        System.IO.File.AppendAllText(logfile_path, append_str);
                    }
                });
                accessing_sem.Release();
            }
            catch (ThreadInterruptedException)
            {
                return;
            }
        }
        public void recv_funtion()
        {
            accessing_sem.WaitOne();
            this.Invoke((MethodInvoker)delegate()
            {
                timer2.Enabled = true;
                timer2.Start();
            });
            switch (Rcv_array[1])
            {
                case 'N':
                    {

                        this.Invoke((MethodInvoker)delegate()
                        {
                            timer3.Enabled = true;
                        });
                    }
                    break;
                case '5':
                    {
                        this.Invoke((MethodInvoker)delegate()
                        {
                            if (Rcv_array[2] == 'R')
                            {
                                led_color[0] = 1;
                            }
                            else
                            {
                                led_color[0] = 0;
                            }
                            if (Rcv_array[3] == 'L')
                            {
                                textBox13.BackColor = System.Drawing.SystemColors.Control;
                                led_state[0] = 0;
                            }
                            else if (Rcv_array[3] == 'H')
                            {
                                if (led_color[0] == 1)
                                {
                                    textBox13.BackColor = Color.Red;
                                }
                                else
                                {
                                    textBox13.BackColor = Color.SeaGreen;
                                }
                                led_state[0] = 1;
                            }
                            else
                            {
                                led_state[0] = 2;
                            }
                            timer3.Enabled = true;
                        });
                    }

                    break;
                case '6':
                    {
                        this.Invoke((MethodInvoker)delegate()
                        {
                            if (Rcv_array[2] == 'R')
                            {
                                led_color[1] = 1;
                            }
                            else
                            {
                                led_color[1] = 0;
                            }
                            if (Rcv_array[3] == 'L')
                            {
                                textBox14.BackColor = System.Drawing.SystemColors.Control;
                                led_state[1] = 0;
                            }
                            else if (Rcv_array[3] == 'H')
                            {
                                if (led_color[1] == 1)
                                {
                                    textBox14.BackColor = Color.Red;
                                }
                                else
                                {
                                    textBox14.BackColor = Color.SeaGreen;
                                }
                                led_state[1] = 1;
                            }
                            else
                            {
                                led_state[1] = 2;
                            }
                            timer3.Enabled = true;
                        });
                    }
                    break;
                case '7':
                    {
                        this.Invoke((MethodInvoker)delegate()
                        {
                            if (Rcv_array[2] == 'R')
                            {
                                led_color[2] = 1;
                            }
                            else
                            {
                                led_color[2] = 0;
                            }
                            if (Rcv_array[3] == 'L')
                            {
                                textBox15.BackColor = System.Drawing.SystemColors.Control;
                                led_state[2] = 0;
                            }
                            else if (Rcv_array[3] == 'H')
                            {
                                if (led_color[2] == 1)
                                {
                                    textBox15.BackColor = Color.Red;
                                }
                                else
                                {
                                    textBox15.BackColor = Color.SeaGreen;
                                }
                                led_state[2] = 1;
                            }
                            else
                            {
                                led_state[2] = 2;
                            }
                            timer3.Enabled = true;
                        });
                    }
                    break;
                case 'T':
                    {
                        this.Invoke((MethodInvoker)delegate()
                        {
                            try
                            {
                                string set_time = RxString.Substring(2, 3);
                                textBox2.Text = Convert.ToInt32(set_time).ToString("D");
                                timer2.Stop();
                                timer2.Interval = Convert.ToInt32(set_time) * 10;
                                timer2.Start();
                                timer3.Enabled = true;
                            }
                            catch 
                            {}
                        });
                    }
                    break;
                case 'U':
                    {
                        this.Invoke((MethodInvoker)delegate()
                        {
                            if (Rcv_array[2] == 'N')
                            {
                                textBox1.Text = "通常充電モード";
                            }
                            else
                            {
                                textBox1.Text = "急速充電モード";
                            }
                            timer3.Enabled = true;
                        });
                    }
                    break;
                case 'I':
                    {
                        this.Invoke((MethodInvoker)delegate()
                        {
                            initcmd_flag = true;
                            timer3.Enabled = true;
                        });
                    }
                    break;
                default:
                    break;
            }
            accessing_sem.Release();
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (!serialPort1.IsOpen && radioButton1.Checked)
                {
                    System.IO.File.AppendAllText(logfile_path, DateTime.Now.ToLongTimeString() + ": Connect");
                    serialPort1.Open();
                }
            }
            catch { }
        }

        private void groupBox3_Enter(object sender, EventArgs e)
        {

        }

        private void ovalShape1_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                sending_init.Interrupt();
            }
            catch
            {
            }
            try
            {
                sending_thread.Interrupt();
            }
            catch
            {
            }
            try
            {
                receive_thread.Interrupt();
            }
            catch
            {
            }
            try
            {
                timer3.Stop();
            }
            catch
            {
            }
            try
            {
                timer2.Stop();
            }
            catch
            {
            }
            Application.Exit();
        }

        private void richrichTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            if (led_state[0] == 2)
            {
                if (textBox13.BackColor == System.Drawing.SystemColors.Control)
                {
                    if (led_color[0] == 0)
                    {
                        textBox13.BackColor = Color.SeaGreen;
                    }
                    else
                    {
                        textBox13.BackColor = Color.Red;
                    }
                }
                else
                {
                    textBox13.BackColor = System.Drawing.SystemColors.Control;
                }
            }
            if (led_state[1] == 2)
            {
                if (textBox14.BackColor == System.Drawing.SystemColors.Control)
                {
                    if (led_color[1] == 0)
                    {
                        textBox14.BackColor = Color.SeaGreen;
                    }
                    else
                    {
                        textBox14.BackColor = Color.Red;
                    }
                }
                else
                {
                    textBox14.BackColor = System.Drawing.SystemColors.Control;
                }
            }
            if (led_state[2] == 2)
            {
                if (textBox15.BackColor == System.Drawing.SystemColors.Control)
                {
                    if (led_color[2] == 0)
                    {
                        textBox15.BackColor = Color.SeaGreen;
                    }
                    else
                    {
                        textBox15.BackColor = Color.Red;
                    }
                }
                else
                {
                    textBox15.BackColor = System.Drawing.SystemColors.Control;
                }
            }
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void radioButton5_CheckedChanged(object sender, EventArgs e)
        {
            nack_count = 0;
        }

        private void radioButton6_CheckedChanged(object sender, EventArgs e)
        {
            nack_count = 0;
        }

        private void radioButton8_CheckedChanged(object sender, EventArgs e)
        {
            nack_count = 0;
        }

        private void radioButton7_CheckedChanged(object sender, EventArgs e)
        {
            nack_count = 0;
        }

        private void radioButton10_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void radioButton9_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox4_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                button1_Click(sender, e);
            }
            {
                char c = e.KeyChar;
                if (c != '\b' && !((c <= 0x66 && c >= 0x61) || (c <= 0x46 && c >= 0x41) || (c >= 0x30 && c <= 0x39) || (c == 0x2c)))
                {
                    e.Handled = true;
                }
            }
        }

        private void textBox5_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                button1_Click(sender, e);
            }
            {
                char c = e.KeyChar;
                if (c != '\b' && !((c <= 0x66 && c >= 0x61) || (c <= 0x46 && c >= 0x41) || (c >= 0x30 && c <= 0x39) || (c == 0x2c)))
                {
                    e.Handled = true;
                }
            }
        }

        private void textBox6_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                button1_Click(sender, e);
            }
            {
                char c = e.KeyChar;
                if (c != '\b' && !((c <= 0x66 && c >= 0x61) || (c <= 0x46 && c >= 0x41) || (c >= 0x30 && c <= 0x39) || (c == 0x2c)))
                {
                    e.Handled = true;
                }
            }
        }

        private void textBox7_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox7_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                button1_Click(sender, e);
            }
            {
                char c = e.KeyChar;
                if (c != '\b' && !((c <= 0x66 && c >= 0x61) || (c <= 0x46 && c >= 0x41) || (c >= 0x30 && c <= 0x39) || (c == 0x2c)))
                {
                    e.Handled = true;
                }
            }
        }

        private void textBox8_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                button1_Click(sender, e);
            }
            {
                char c = e.KeyChar;
                if (c != '\b' && !((c <= 0x66 && c >= 0x61) || (c <= 0x46 && c >= 0x41) || (c >= 0x30 && c <= 0x39) || (c == 0x2c)))
                {
                    e.Handled = true;
                }
            }
        }

        private void textBox4_Leave(object sender, EventArgs e)
        {
            Control control = (Control)sender;
            if (control.Text.Length == 0)
            {
                control.Text = "00000000";
            }
            else
            {
                control.Text = (int.Parse(control.Text, System.Globalization.NumberStyles.HexNumber)).ToString("x8").ToUpper();
            }
        }

        private void textBox5_Leave(object sender, EventArgs e)
        {
            if (textBox5.Text.Length == 0)
            {
                textBox5.Text = "00000000";
            }
            else
            {
                textBox5.Text = (int.Parse(textBox5.Text, System.Globalization.NumberStyles.HexNumber)).ToString("x8").ToUpper();
            }
        }
        private void textBox6_Leave(object sender, EventArgs e)
        {
            if (textBox6.Text.Length == 0)
            {
                textBox6.Text = "00000000";
            }
            else
            {
                textBox6.Text = (int.Parse(textBox6.Text, System.Globalization.NumberStyles.HexNumber)).ToString("x8").ToUpper();
            }
        }

        private void textBox7_Leave(object sender, EventArgs e)
        {
            if (textBox7.Text.Length == 0)
            {
                textBox7.Text = "00000000";
            }
            else
            {
                textBox7.Text = (int.Parse(textBox7.Text, System.Globalization.NumberStyles.HexNumber)).ToString("x8").ToUpper();
            }
        }

        private void textBox8_Leave(object sender, EventArgs e)
        {
            if (textBox8.Text.Length == 0)
            {
                textBox8.Text = "00000000";
            }
            else
            {
                textBox8.Text = (int.Parse(textBox8.Text, System.Globalization.NumberStyles.HexNumber)).ToString("x8").ToUpper();
            }
        }

        private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
        {
            {
                char c = e.KeyChar;
                if (c != '\b' && !((c >= 0x30 && c <= 0x39)))
                {
                    e.Handled = true;
                }
            }
        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            timer3.Stop();
            if (initcmd_flag)
            {
                sending_init = new Thread(sendinginit_funtion);
                sending_init.Start();
                initcmd_flag = false;
            }
            else
            {
                sending_thread = new Thread(sending_funtion);
                sending_thread.Start();
            }
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            timer3.Interval = (int)numericUpDown1.Value * 10;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {

            try
            {
                sending_init.Interrupt();
            }
            catch
            {
            }
            try
            {
                sending_thread.Interrupt();
            }
            catch
            {
            }
            try
            {
                receive_thread.Interrupt();
            }
            catch
            {
            }
            try
            {
                timer3.Stop();
            }
            catch
            {
            }
            try
            {
                timer2.Stop();
            }
            catch
            {
            }
        }
    }
}
